package com.hwpt.chesedemo.presentation.viewmodel

import android.content.Context
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.hwpt.chesedemo.data.local.PreferenceManager
import com.hwpt.chesedemo.presentation.theme.LanguageManager
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch

class SettingsViewModel : ViewModel() {

    var currentLanguageCode by mutableStateOf(LanguageManager.currentLanguageCode)
        private set

    var showLanguageDialog by mutableStateOf(false)
        private set

    // 加载保存的语言设置
    fun loadLanguageSettings(context: Context) {
        viewModelScope.launch {
            val savedLanguage = PreferenceManager.getLanguage(context).first()
            currentLanguageCode = savedLanguage
            LanguageManager.currentLanguageCode = savedLanguage
        }
    }

    // 更新语言代码
    fun updateLanguageCode(languageCode: String) {
        currentLanguageCode = languageCode
    }

    // 显示语言选择对话框
    fun showLanguageDialog() {
        showLanguageDialog = true
    }

    // 隐藏语言选择对话框
    fun hideLanguageDialog() {
        showLanguageDialog = false
    }

    // 更改语言
    fun changeLanguage(context: Context, languageCode: String) {
        viewModelScope.launch {
            LanguageManager.setLanguage(context, languageCode)
            currentLanguageCode = languageCode
            hideLanguageDialog()
        }
    }

    // 获取当前语言的显示名称
    fun getCurrentLanguageName(): String {
        return getLanguageDisplayName(currentLanguageCode)
    }

    // 辅助函数：根据语言代码获取显示名称
    private fun getLanguageDisplayName(languageCode: String): String {
        return when (languageCode) {
            "zh" -> "中文"
            "en" -> "English"
            "ja" -> "日本語"
            "ko" -> "한국어"
            "es" -> "Español"
            "fr" -> "Français"
            "de" -> "Deutsch"
            "ru" -> "Русский"
            else -> "English"
        }
    }
}